﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

using System.Web;
using System.Web.Mvc;
using OBUCare.Core.Common;

namespace OBUCare.Web.Infrastructure
{
    /// <summary>
    /// 专门用于导出Excel报表的助手类
    /// </summary>
    public class ExportHelper
    {
       

        /// <summary>
        ///模板文件
        /// </summary>
        private string template;

        /// <summary>
        /// 保存导出结果的临时文件
        /// </summary>
        private string newTempFile;

        /// <summary>
        /// 用于导出的Excel对象
        /// </summary>
        NPOIExcelHelper excel;

        /// <summary>
        /// 上次操作的行号,上次已经将值写到第5行，则这个参数就为5，我们要操作的下一行，就是第六行。如果更新了行号一定要将值改回去
        /// </summary>
        public int LastRowIndex { get; set; }
        ///// <summary>
        ///// 上次操作的列号,上次已经将值写到第5列，则这个参数就为5，我们要操作的下一列，就是第六列。如果更新了列号一定要将值改回去
        ///// </summary>
        //public int LastColIndex { get; set; }

        public ExportHelper(string template)
        {
            this.template = template;

            //随机生成新文件名，以务重名
            newTempFile = Path.Combine(UIUtility.GetTempFolderPath(), Path.GetFileName(template).GetNewRandomFileName());

        }

        /// <summary>
        /// 导出列表到Excel
        /// </summary>
        /// <typeparam name="T">导出列表对象的类型</typeparam>
        /// <param name="items">待导出的数据</param>
        /// <param name="colBuilder">构造获取行中待导出列的值的委托</param>
        /// <param name="template">模板文件</param>
        /// <param name="startRowIndex">导出的起始行号</param>
        /// <param name="startColIndex">导出</param>
        /// <returns></returns>
        public void ExportToExcel<T>(IEnumerable<T> items, Action<T,NPOIExcelHelper,int> writer, int sheetIndex, int startRowIndex)
        {           
            try
            {
                if(excel==null) 
                    excel=new NPOIExcelHelper(template);
                
                excel.ActiveSheetIndex = sheetIndex;
                ////获取字段值的委托列表
                //IList<Func<T, string>> getColValuefunc = new List<Func<T, string>>();

                ////加载获取列值的方法集合
                //colBuilder(getColValuefunc);

                int rowIndex = startRowIndex; //导出时起始行号
               
                
                items.Each(item =>
                {
                    //columnIndex = startColIndex; //起始列号
                    //getColValuefunc.Each(f =>
                    //{
                    //    var text = f(item);
                    //    excel[rowIndex, columnIndex++] = text;
                    //});

                    writer(item, excel, rowIndex);

                    rowIndex++;
                });

                this.LastRowIndex = rowIndex - 1;
              
            }
            catch(Exception ex) 
            {
                var msg = ex.Message;
                throw ex;
            }  
        }

        /// <summary>
        /// 导出主要数据后，还需导入一些额外数据
        /// </summary>
        /// <param name="action">
        /// 导出额外数据的委托,第一个参数为：Excel对象
        /// 第二个参数为导出本象本身，主要是为了能访问对象里的部分值，比如上次操作的行号及列号
        /// </param>
        public void ExportAddionalInfomation(Action<NPOIExcelHelper,ExportHelper> action)
        {
            if (excel == null)
                excel = new NPOIExcelHelper(template);
            action(this.excel,this);
        }

        public ActionResult DownLoad(Func<string, string, string, FilePathResult> downFunc, string fileName)
        {
            excel.SaveAs(this.newTempFile);

            //var cd = new System.Net.Mime.ContentDisposition
            //{
            //    // for example foo.bak
            //    FileName = fileName,

            //    // always prompt the user for downloading, set to true if you want 
            //    // the browser to try to show the file inline
            //    Inline = false,
            //};
            //response.AppendHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"",fileName));

            return downFunc(newTempFile, "application/vnd.ms-excel", HttpUtility.UrlEncode(fileName));
        }

        public static ActionResult HandleExportException(Controller c, Exception ex, string fileName)
        {
            //c.Response.StatusCode = 500;
            //c.Response.AppendHeader("message", string.Format("{0}导出失败:{1}！", fileName,ex.Message));
            string errorMsg = string.Format("{0}导出失败:{1}！", fileName, ex.Message);
            var r = new ContentResult();
            r.Content = String.Format("<Script>alert('{0}！');</Script>", errorMsg);
            r.ContentType = "text/plain";
            return r;
        }

    }
}